<script lang="jsx" setup>
import { reactive, ref } from 'vue';
import dayjs from 'dayjs';
import { ArrowDownOutlined, DeleteOutlined, EditOutlined, PlusOutlined, SearchOutlined } from '@ant-design/icons-vue';
import { useElementSize } from '@vueuse/core';
import useResetTableRef from '@/hooks/common/resetTableRef';
import { downloadMiFile, printPdf } from '@/service/api/modules/engineering-manage/engineering-data-inquiry';

import CustomerComplaintPictures from './module/customer-complaint-pictures.vue';
const commonSearchRef = ref(null);
const [searchParams, searchParamsReset] = useResetTableRef({
  moduleNo: null,
  moduleNoState: '8'
});

const { height } = useElementSize(commonSearchRef);

const stateLabels = {
  0: '编写',
  1: '更改',
  2: '待处理',
  3: '编写中',
  4: '暂停',
  5: '已回退',
  6: '反审核',
  7: '审核中',
  8: '已上网',
  9: '完成',
  10: '取消',
  11: '外部ECN',
  12: '外部ECN待处理',
  13: '内部ECN',
  19: '样板转生产',
  20: 'ENC更改',
  25: '报废',
  27: '申请',
  28: '入库',
  29: '发放',
  34: '归还',
  35: '接收',
  36: '审核',
  37: '确认',
  100: 'PPC审核'
};

const tableRef = ref(null);
const formList = [
  {
    type: 'input',
    key: 'moduleNo',
    label: '生产型号',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 4,
    placeholder: '请输入生产型号',
    showTime: true
  },
  {
    type: 'input',
    key: 'moduleNo',
    label: '客诉编号',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 4,
    placeholder: '请输入客诉编号',
    showTime: true
  },
  {
    type: 'input',
    key: 'moduleNo',
    label: '日期范围',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 4,
    placeholder: '请选择日期范围',
    showTime: true
  },
  {
    type: 'select',
    key: 'moduleNoState',
    label: '查看方式',
    placeholder: '请选择查看方式',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 4,
    selectOptions: getStateList()
  }
];

function getTextColor(v) {
  let state = Number(v);
  if (state === 1409171046440000 || state === 1609131645440000)
    // 流程初审
    state = 2;
  else if (state === 1409171046540000 || state === 1409191117540000)
    // 流程复审
    state = 3;
  else if (state === 1610130953480000 || state === 1409191117380000)
    // 签名
    state = 4;

  switch (Number(state)) {
    case -1:
      return '#FF0000';
    case 0:
      return '#0080FF';
    case 1:
      return '#FFA500';
    case 2:
      return '#FF8000';
    case 3:
      return '#B15BFF';
    case 4:
      return '#73BF00';
    case 5:
      return '#8E8E8E';
    case 6:
      return '#BEBEBE';
    case 7:
      return '#FF0000';
    case 8:
      return '#4682B4';
    case 9:
      return '#0000FF';
    case 10:
      return '#007500';
    default:
      return '#0000FF';
  }
}

function getStateList() {
  return Object.entries(stateLabels).map(([key, value]) => {
    if (key === 8) {
      return {
        label: '全部',
        value: key
      };
    }
    return {
      label: value,
      value: key
    };
  });
}

const leftColumn = [
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 70,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'state',
    dataIndex: 'state',
    title: '状态',
    align: 'center',
    checked: true,
    ellipsis: true,
    customFilterDropdown: true,
    width: 130,
    onFilter: (value, record) => {
      let state = Number(record.state);
      if (state === 1409171046440000 || state === 1609131645440000)
        // 流程初审
        state = 2;
      else if (state === 1409171046540000 || state === 1409191117540000)
        // 流程复审
        state = 3;
      else if (state === 1610130953480000 || state === 1409191117380000)
        // 签名
        state = 4;
      if (value) {
        return Number(value) === Number(state);
      }
      return true;
    },
    customRender: ({ record }) => {
      let state = Number(record.state);

      if (state === 1409171046440000 || state === 1609131645440000)
        // 流程初审
        state = 2;
      else if (state === 1409171046540000 || state === 1409191117540000)
        // 流程复审
        state = 3;
      else if (state === 1610130953480000 || state === 1409191117380000)
        // 签名
        state = 4;

      if (state === 8) {
        return (
          <div class="h-full w-full" title="已上网" style={{ color: getTextColor(record.state) }}>
            已上网
          </div>
        );
      }
      return (
        <div class="h-full w-full" title={stateLabels[state] || ''} style={{ color: getTextColor(record.state) }}>
          {stateLabels[state] || ''}
        </div>
      );
    }
  },
  {
    key: 'moduleNo',
    dataIndex: 'moduleNo',
    title: '生产型号',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 160,
    customRender: ({ record }) => {
      return <span class="fonw-800 color-#646cff">{record.moduleNo}</span>;
    }
  },
  {
    key: 'pnType',
    dataIndex: 'pnType',
    title: '类型',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 130
  },
  {
    key: 'prodType',
    dataIndex: 'prodType',
    title: '产品类型',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 130
  },
  {
    key: 'surfTrea1',
    dataIndex: 'surfTrea1',
    title: '表面处理1',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 130
  },
  {
    key: 'peType',
    dataIndex: 'peType',
    title: '板类型',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 130
  },
  {
    key: 'peDifficulty',
    dataIndex: 'peDifficulty',
    title: '开发等级',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 130
  },
  {
    key: 'peState',
    dataIndex: 'peState',
    title: '生产稿状态',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 130
  },
  {
    key: 'peSpecial',
    dataIndex: 'peSpecial',
    title: '特殊周期',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 130
  },
  {
    key: 'pemark',
    dataIndex: 'pemark',
    title: '水印',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 130
  },
  {
    key: 'peRemark',
    dataIndex: 'peRemark',
    title: '工程备注',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 130
  },
  {
    key: 'targetName',
    dataIndex: 'targetName',
    title: '终端客户',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 130
  },
  {
    key: 'custNo',
    dataIndex: 'custNo',
    title: '客户编码',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 130
  },
  {
    key: 'custProdNo',
    dataIndex: 'custProdNo',
    title: '客户型号',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 130
  },
  {
    key: 'custProdNoAdd',
    dataIndex: 'custProdNoAdd',
    title: '物料号',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 130
  },
  {
    key: 'peActive',
    dataIndex: 'peActive',
    title: 'PE状态',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 130,
    customRender: ({ record }) => {
      return record.peactive ? '有效' : '过期';
    }
  },
  {
    key: 'activeRemark',
    dataIndex: 'activeRemark',
    title: '操作备注',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 130
  },
  {
    key: 'mktActive',
    dataIndex: 'mktActive',
    title: 'MIKT投产',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 130,
    customRender: ({ record }) => {
      return record.mktactive ? '是' : '否';
    }
  },
  {
    key: 'weight',
    dataIndex: 'weight',
    title: '单重',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 130
  },
  {
    key: 'remark',
    dataIndex: 'remark',
    title: '备注',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 130
  },
  {
    key: 'createBy',
    dataIndex: 'createBy',
    title: '创建人',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 130
  },
  {
    key: 'createDate',
    dataIndex: 'createDate',
    title: '创建时间',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 160,
    customRender: ({ record }) => {
      return dayjs(record.createDate).format('YYYY-MM-DD HH:mm:ss');
    }
  },
  {
    key: 'updateDate',
    dataIndex: 'updateDate',
    // title: <SortTableTitle title="最后修改时间"></SortTableTitle>,
    title: '最后修改时间',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 160,
    customRender: ({ record }) => {
      return dayjs(record.updateDate).format('YYYY-MM-DD HH:mm:ss');
    }
  }
];

const state = reactive({
  searchText: '',
  searchedColumn: ''
});

// 状态筛选
const selectRef = ref(null);
const handleSearch = (selectedKeys, confirm, dataIndex) => {
  confirm();
  state.searchText = selectedKeys[0];
  state.searchedColumn = dataIndex;
};

const handleReset = clearFilters => {
  clearFilters();
  state.searchText = '';
};

const centerRemark = ref('工艺备注');

const centerTableRef = ref(null);
const centerSearchParams = ref({
  prodId: null
});

const activeKey = ref('1');

const currentLeftTableRow = ref({});

const engineeringInstructionTableRef = ref(null);
const customerComplaintPicturesRef = ref(null);
const engineeringDrawingRef = ref(null);
const processcustomerComplaintPicturesRef = ref(null);
const productionToolsRef = ref(null);

function search() {
  tableRef.value.getData(1);
}

function reset() {
  searchParamsReset();
  search();
}

function tableCustomCell(record) {
  if (record.peactive && record.issActive == 0 && record.lotActive == 0) {
    return {
      class: 'red'
    };
  }
  return {};
}

function handleLeftTableLoadSuccess(data) {
  if (!data?.length) return;
  tableRef.value.setCurrentRowId(data[0]);
  handleLeftTableRowClick(data[0]);
}

// 左侧表格部分点击
function handleLeftTableRowClick(row) {
  console.log('row', row);

  currentLeftTableRow.value = row;
  centerSearchParams.value.prodId = row.prodId;
  centerRemark.value = '工艺备注';
  centerTableRef.value.getData(1);

  // 工程文件tab查询
  customerComplaintPicturesRef.value.getData({
    prodNo: currentLeftTableRow.value.moduleNo
  });

  // if(!row.issActive){

  // }
}

// 中间部门表格部分点击
function handleCenterTableRowClick(row) {
  centerRemark.value = row?.remark?.replace(/\n/g, '<br>');
  // 工程制表tab查询
  engineeringInstructionTableRef.value.getData({
    prodId: centerSearchParams.value.prodId,
    techId: row.techId
  });

  // 生产工具tab查询
  productionToolsRef.value.getData({
    techId: row.techId
  });

  // 工艺工程文件tab查询
  processcustomerComplaintPicturesRef.value.getData({
    techId: row.techId
  });

  // 工程图纸查询
  engineeringDrawingRef.value.getData({
    prodNo: currentLeftTableRow.value.moduleNo,
    techId: row.techId
  });
}

function handleCenterTableLoadSuccess(data) {
  if (!data?.length) return;
  centerTableRef.value.setCurrentRowId(data[0]);
  handleCenterTableRowClick(data[0]);
}

function handleDownload(data) {
  printPdf(
    {
      prodId: currentLeftTableRow.value.prodId,
      techId: data.record.techId
    },
    `${currentLeftTableRow.value.moduleNo}-${data.record.techName}`
  );
  data.hidePopup();
}
const isLocalHost = window.location.hostname === 'localhost';
const visible = ref(false);
const previewData = ref(null);
const previewTitle = ref(null);
function handlePreview(data) {
  visible.value = true;
  previewTitle.value = `${currentLeftTableRow.value.moduleNo}-${data.record.techName}工程指示数据.pdf 预览`;
  previewData.value = `${isLocalHost ? 'http://192.168.166.169:9999/dev-api/' : '/dev-api/'}erpsyncmes/mi/print/getPdf?prodId=${currentLeftTableRow.value.prodId}&techId=${data.record.techId}`;
  data.hidePopup();
}

// MI下载
function handleMiDownload(data) {
  downloadMiFile(
    {
      prodId: currentLeftTableRow.value.prodId
    },
    data.record.moduleNo
  );
  data.hidePopup();
}

// MI预览
function handleMiPreview(data) {
  visible.value = true;
  previewTitle.value = `${currentLeftTableRow.value.moduleNo}MI文件.pdf 预览`;
  previewData.value = `${isLocalHost ? 'http://192.168.166.169:9999/dev-api/' : '/dev-api/'}erpsyncmes/mi/print/getMiPdf?prodId=${currentLeftTableRow.value.prodId}`;
  data.hidePopup();
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-8px overflow-hidden lt-sm:overflow-auto">
    <CommonSearch
      ref="commonSearchRef"
      v-model:searchParams="searchParams"
      :form-list="formList"
      @search="search"
      @reset="reset"
    ></CommonSearch>
    <ARow :gutter="8" class="h-full w-full" :style="{ height: `calc(100% - ${height}px)` }">
      <ACol :span="16" class="h-full min-h-500px flex-col-stretch gap-8px overflow-hidden lt-sm:overflow-auto">
        <Table
          ref="tableRef"
          v-model:searchParams="searchParams"
          :column="leftColumn"
          :show-row-selection="false"
          row-key="prodId"
          :scroll="{ y: 'auto' }"
          is-init-get-data
          url="/erpsyncmes/Mi/findModuleNo"
          :auto-generate-uuid="false"
          class="h-full"
          :table-custom-cell="tableCustomCell"
          :show-quick-jumper="false"
          :default-expand-all-rows="true"
          @table-row-click="handleLeftTableRowClick"
          @table-data-load-sucess="handleLeftTableLoadSuccess"
        >
          <template #title>
            <span class="mr-8px color-#646cff">客诉信息</span>
            <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="addData">
              <template #icon>
                <PlusOutlined class="align-sub" />
              </template>
              新增
            </AButton>
            <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="updata">
              <template #icon>
                <EditOutlined class="align-sub" />
              </template>
              修改
            </AButton>
            <!-- 删除 -->
            <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="deleteData">
              <template #icon>
                <DeleteOutlined class="align-sub" />
              </template>
              删除
            </AButton>
            <!-- 导出 -->
            <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="deleteData">
              <template #icon>
                <ArrowDownOutlined class="align-sub" />
              </template>
              导出
            </AButton>
          </template>
          <template #filterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
            <div class="p-8px">
              <ASelect
                ref="selectRef"
                class="mb-8px block w-188px"
                placeholder="请选择查看方式"
                show-search
                :value="selectedKeys[0]"
                allow-clear
                @change="
                  e => {
                    setSelectedKeys([e]);
                  }
                "
              >
                <ASelectOption v-for="item in getStateList()" :key="item.value" :value="item.value">
                  {{ item.label }}
                </ASelectOption>
              </ASelect>

              <AButton
                type="primary"
                size="small"
                class="mr-8px w-90px"
                @click="handleSearch(selectedKeys, confirm, column.dataIndex)"
              >
                <template #icon><SearchOutlined /></template>
                搜索
              </AButton>
              <AButton size="small" class="w-90px" @click="handleReset(clearFilters)">重置</AButton>
            </div>
          </template>
          <template #contextmenuPopup-orter="{ args }">
            <li class="popup-item" @click="handleMiDownload(args)">
              <SvgIcon local-icon="download" class="text-16px" />
              下载
            </li>
            <li class="popup-item" @click="handleMiPreview(args)">
              <SvgIcon local-icon="preview" class="text-16px" />
              预览
            </li>
          </template>
        </Table>

        <ACard class="min-h-300px" :body-style="{ padding: '15px', paddingBottom: '25px' }">
          <div>客诉图表统计</div>
        </ACard>
      </ACol>
      <ACol :span="8" class="right-table h-full">
        <CustomerComplaintPictures ref="customerComplaintPicturesRef" />
      </ACol>
    </ARow>
    <FileViwer v-model:visible="visible" :url="previewData" type="pdf" pdf-use-iframe :title="previewTitle" />
  </div>
</template>

<style lang="scss" scoped>
.module-no-info {
  align-items: center;
  margin-bottom: 5px;
  &:last-child {
    margin-bottom: 0;
  }
  .icon {
    display: flex;
    align-items: center;
    margin-right: 15px;
    .icon-warp {
      width: 24px;
      height: 24px;
      text-align: center;
      line-height: 24px;
      border-radius: 6px;
      background: rgb(230, 244, 255);
      .iconfont {
        color: rgb(9, 88, 217);
        font-size: 14px;
      }
    }
  }
  .content {
    font-size: 14px;
    display: flex;
    .label {
      margin-right: 5px;
      font-weight: 700;
      &::after {
        content: ':';
      }
    }
    .data {
      text-decoration: underline;
      color: #646cff;
    }
  }
}

.right-table {
  :deep(.ant-tabs) {
    .ant-tabs-nav {
      margin-bottom: 0;
    }

    .ant-tabs-content-holder {
      height: calc(100% - 40px);
      .ant-tabs-content {
        height: 100%;
        .ant-tabs-tabpane {
          height: 100%;
        }
      }
    }
    .ant-tabs-nav-list {
      .ant-tabs-tab {
        border-radius: 6px 6px 0 0;
      }
      .ant-tabs-tab-active {
        background: #646cff;
        .ant-tabs-tab-btn {
          color: #fff;
        }
      }
    }
  }
}
</style>
